/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.hw.common.utils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.BinaryJedisCluster;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * jedisCluster Cache 工具类
 *
 * @author ThinkGem
 * @version 2014-6-29
 */
public class BinaryJedisClusterUtils {
   
   private static Logger logger = LoggerFactory
         .getLogger(BinaryJedisClusterUtils.class);
   
   private static BinaryJedisCluster binaryJedisCluster = SpringContextHolder
         .getBean(BinaryJedisCluster.class);
   
   /**
    * 获取缓存
    *
    * @param key 键
    * @return 值
    */
   public static String get(String key) {
      byte[] value = null;
      try {
         if (binaryJedisCluster.exists(getBytesKey(key))) {
            value = binaryJedisCluster.get(getBytesKey(key));
            if (value == null)
               return null;
            String sValue = new String(value);
            sValue = StringUtils.isNotBlank(sValue)
                  && !"nil".equalsIgnoreCase(sValue) ? sValue : null;
            logger.debug("get {} = {}", key, sValue);
            return sValue;
         }
      } catch (Exception e) {
         logger.warn("get {} = {}", key, value, e);
      } finally {
         
      }
      return null;
   }
   
   /**
    * 获取缓存
    *
    * @param key 键
    * @return 值
    */
   public static Object getObject(String key) {
      Object value = null;
      
      try {
         
         if (binaryJedisCluster.exists(getBytesKey(key))) {
            value = toObject(binaryJedisCluster.get(getBytesKey(key)));
            logger.debug("getObject {} = {}", key, value);
         }
      } catch (Exception e) {
         logger.warn("getObject {} = {}", key, value, e);
      } finally {
         
      }
      return value;
   }
   
   /**
    * 设置缓存
    *
    * @param key          键
    * @param value        值
    * @param cacheSeconds 超时时间，0为不超时
    * @return
    */
   public static String set(String key, String value, int cacheSeconds) {
      String result = null;
      
      try {
         
         result = binaryJedisCluster.set(getBytesKey(key),
               getBytesKey(value));
         if (cacheSeconds != 0) {
            binaryJedisCluster.expire(getBytesKey(key), cacheSeconds);
         }
         logger.debug("set {} = {}", key, value);
      } catch (Exception e) {
         logger.warn("set {} = {}", key, value, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 设置缓存
    *
    * @param key          键
    * @param value        值
    * @param cacheSeconds 超时时间，0为不超时
    * @return
    */
   public static String setObject(String key, Object value, int cacheSeconds) {
      String result = null;
      try {
         result = binaryJedisCluster.set(getBytesKey(key), toBytes(value));
         if (cacheSeconds != 0) {
            binaryJedisCluster.expire(getBytesKey(key), cacheSeconds);
         }
         logger.debug("setObject {} = {}", key, value);
      } catch (Exception e) {
         logger.warn("setObject {} = {}", key, value, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 获取List缓存
    *
    * @param key 键
    * @return 值
    */
   public static List<byte[]> getList(String key) {
      List<byte[]> value = null;
      
      try {
         
         if (binaryJedisCluster.exists(getBytesKey(key))) {
            value = binaryJedisCluster.lrange(getBytesKey(key), 0, -1);
            logger.debug("getList {} = {}", key, value);
         }
      } catch (Exception e) {
         logger.warn("getList {} = {}", key, value, e);
      } finally {
         
      }
      return value;
   }
   
   /**
    * 获取List缓存
    *
    * @param key 键
    * @return 值
    */
   public static List<Object> getObjectList(String key) {
      List<Object> value = null;
      
      try {
         
         if (binaryJedisCluster.exists(getBytesKey(key))) {
            List<byte[]> list = binaryJedisCluster.lrange(getBytesKey(key),
                  0, -1);
            value = Lists.newArrayList();
            for (byte[] bs : list) {
               value.add(toObject(bs));
            }
            logger.debug("getObjectList {} = {}", key, value);
         }
      } catch (Exception e) {
         logger.warn("getObjectList {} = {}", key, value, e);
      } finally {
         
      }
      return value;
   }
   
   /**
    * 设置List缓存
    *
    * @param key          键
    * @param value        值
    * @param cacheSeconds 超时时间，0为不超时
    * @return
    */
   public static long setList(String key, List<byte[]> value, int cacheSeconds) {
      long result = 0;
      
      try {
         
         if (binaryJedisCluster.exists(getBytesKey(key))) {
            binaryJedisCluster.del(getBytesKey(key));
         }
         result = binaryJedisCluster.rpush(getBytesKey(key),
               (byte[][]) value.toArray());
         if (cacheSeconds != 0) {
            binaryJedisCluster.expire(getBytesKey(key), cacheSeconds);
         }
         logger.debug("setList {} = {}", key, value);
      } catch (Exception e) {
         logger.warn("setList {} = {}", key, value, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 设置List缓存
    *
    * @param key          键
    * @param value        值
    * @param cacheSeconds 超时时间，0为不超时
    * @return
    */
   public static long setObjectList(String key, List<Object> value,
                                    int cacheSeconds) {
      long result = 0;
      
      try {
         
         if (binaryJedisCluster.exists(getBytesKey(key))) {
            binaryJedisCluster.del(getBytesKey(key));
         }
         List<byte[]> list = Lists.newArrayList();
         for (Object o : value) {
            list.add(toBytes(o));
         }
         result = binaryJedisCluster.rpush(getBytesKey(key),
               (byte[][]) list.toArray());
         if (cacheSeconds != 0) {
            binaryJedisCluster.expire(getBytesKey(key), cacheSeconds);
         }
         logger.debug("setObjectList {} = {}", key, value);
      } catch (Exception e) {
         logger.warn("setObjectList {} = {}", key, value, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 向List缓存中添加值
    *
    * @param key   键
    * @param value 值
    * @return
    */
   public static long listAdd(String key, String... value) {
      long result = 0;
      
      try {
         result = binaryJedisCluster.rpush(getBytesKey(key),
               getBytesKey(value));
         logger.debug("listAdd {} = {}", key, value);
      } catch (Exception e) {
         logger.warn("listAdd {} = {}", key, value, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 向List缓存中添加值
    *
    * @param key   键
    * @param value 值
    * @return
    */
   public static long listObjectAdd(String key, Object... value) {
      long result = 0;
      try {
         List<byte[]> list = Lists.newArrayList();
         for (Object o : value) {
            list.add(toBytes(o));
         }
         result = binaryJedisCluster.rpush(getBytesKey(key),
               (byte[][]) list.toArray());
         logger.debug("listObjectAdd {} = {}", key, value);
      } catch (Exception e) {
         logger.warn("listObjectAdd {} = {}", key, value, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 获取缓存
    *
    * @param key 键
    * @return 值
    */
   public static Set<String> getSet(String key) {
      Set<String> value = null;
      try {
         if (binaryJedisCluster.exists(getBytesKey(key))) {
            value = Sets.newHashSet();
            Set<byte[]> set = binaryJedisCluster.smembers(getBytesKey(key));
            for (byte[] bs : set) {
               value.add(new String(bs));
            }
            logger.debug("getSet {} = {}", key, value);
         }
      } catch (Exception e) {
         logger.warn("getSet {} = {}", key, value, e);
      } finally {
         
      }
      return value;
   }
   
   /**
    * 获取缓存
    *
    * @param key 键
    * @return 值
    */
   public static Set<Object> getObjectSet(String key) {
      Set<Object> value = null;
      try {
         if (binaryJedisCluster.exists(getBytesKey(key))) {
            value = Sets.newHashSet();
            Set<byte[]> set = binaryJedisCluster.smembers(getBytesKey(key));
            for (byte[] bs : set) {
               value.add(toObject(bs));
            }
            logger.debug("getObjectSet {} = {}", key, value);
         }
      } catch (Exception e) {
         logger.warn("getObjectSet {} = {}", key, value, e);
      } finally {
         
      }
      return value;
   }
   
   /**
    * 设置Set缓存
    *
    * @param key          键
    * @param value        值
    * @param cacheSeconds 超时时间，0为不超时
    * @return
    */
   public static long setSet(String key, Set<String> value, int cacheSeconds) {
      long result = 0;
      try {
         if (binaryJedisCluster.exists(getBytesKey(key))) {
            binaryJedisCluster.del(getBytesKey(key));
         }
         Set<byte[]> set = Sets.newHashSet();
         for (String s : value) {
            set.add(s.getBytes());
         }
         result = binaryJedisCluster.sadd(getBytesKey(key), (byte[][]) set.toArray());
         if (cacheSeconds != 0) {
            binaryJedisCluster.expire(getBytesKey(key), cacheSeconds);
         }
         logger.debug("setSet {} = {}", key, value);
      } catch (Exception e) {
         logger.warn("setSet {} = {}", key, value, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 设置Set缓存
    *
    * @param key          键
    * @param value        值
    * @param cacheSeconds 超时时间，0为不超时
    * @return
    */
   public static long setObjectSet(String key, Set<Object> value,
                                   int cacheSeconds) {
      long result = 0;
      
      try {
         
         if (binaryJedisCluster.exists(getBytesKey(key))) {
            binaryJedisCluster.del(getBytesKey(key));
         }
         Set<byte[]> set = Sets.newHashSet();
         for (Object o : value) {
            set.add(toBytes(o));
         }
         result = binaryJedisCluster.sadd(getBytesKey(key), (byte[][]) set.toArray());
         if (cacheSeconds != 0) {
            binaryJedisCluster.expire(getBytesKey(key), cacheSeconds);
         }
         logger.debug("setObjectSet {} = {}", key, value);
      } catch (Exception e) {
         logger.warn("setObjectSet {} = {}", key, value, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 向Set缓存中添加值
    *
    * @param key   键
    * @param value 值
    * @return
    */
   public static long setSetAdd(String key, String... value) {
      long result = 0;
      try {
         result = binaryJedisCluster.sadd(getBytesKey(key), getBytesKey(value));
         logger.debug("setSetAdd {} = {}", key, value);
      } catch (Exception e) {
         logger.warn("setSetAdd {} = {}", key, value, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 向Set缓存中添加值
    *
    * @param key   键
    * @param value 值
    * @return
    */
   public static long setSetObjectAdd(String key, Object... value) {
      long result = 0;
      
      try {
         
         Set<byte[]> set = Sets.newHashSet();
         for (Object o : value) {
            set.add(toBytes(o));
         }
         result = binaryJedisCluster.rpush(getBytesKey(key), (byte[][]) set.toArray());
         logger.debug("setSetObjectAdd {} = {}", key, value);
      } catch (Exception e) {
         logger.warn("setSetObjectAdd {} = {}", key, value, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 获取Map缓存
    *
    * @param key 键
    * @return 值
    */
   public static Map<String, String> getMap(String key) {
      Map<String, String> value = null;
      
      try {
         value = Maps.newHashMap();
         if (binaryJedisCluster.exists(getBytesKey(key))) {
            Map<byte[], byte[]> map = binaryJedisCluster.hgetAll(getBytesKey(key));
            for (Map.Entry<byte[], byte[]> e : map.entrySet()) {
               value.put(new String(e.getKey()), new String(e.getValue()));
            }
            logger.debug("getMap {} = {}", key, value);
         }
      } catch (Exception e) {
         logger.warn("getMap {} = {}", key, value, e);
      } finally {
         
      }
      return value;
   }
   
   /**
    * 获取Map缓存
    *
    * @param key 键
    * @return 值
    */
   public static Map<String, Object> getObjectMap(String key) {
      Map<String, Object> value = null;
      
      try {
         
         if (binaryJedisCluster.exists(getBytesKey(key))) {
            value = Maps.newHashMap();
            Map<byte[], byte[]> map = binaryJedisCluster.hgetAll(getBytesKey(key));
            for (Map.Entry<byte[], byte[]> e : map.entrySet()) {
               value.put(new String(e.getKey()), toObject(e.getValue()));
            }
            logger.debug("getObjectMap {} = {}", key, value);
         }
      } catch (Exception e) {
         logger.warn("getObjectMap {} = {}", key, value, e);
      } finally {
         
      }
      return value;
   }
   
   /**
    * 设置Map缓存
    *
    * @param key          键
    * @param value        值
    * @param cacheSeconds 超时时间，0为不超时
    * @return
    */
   public static String setMap(String key, Map<String, String> value,
                               int cacheSeconds) {
      String result = null;
      
      try {
         
         if (binaryJedisCluster.exists(getBytesKey(key))) {
            binaryJedisCluster.del(getBytesKey(key));
         }
         Map<byte[], byte[]> map = Maps.newHashMap();
         for (Map.Entry<String, String> e : value.entrySet()) {
            map.put(e.getKey().getBytes(), e.getValue().getBytes());
         }
         result = binaryJedisCluster.hmset(getBytesKey(key), map);
         if (cacheSeconds != 0) {
            binaryJedisCluster.expire(getBytesKey(key), cacheSeconds);
         }
         logger.debug("setMap {} = {}", key, value);
      } catch (Exception e) {
         logger.warn("setMap {} = {}", key, value, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 设置Map缓存
    *
    * @param key          键
    * @param value        值
    * @param cacheSeconds 超时时间，0为不超时
    * @return
    */
   public static String setObjectMap(String key, Map<String, Object> value,
                                     int cacheSeconds) {
      String result = null;
      
      try {
         
         if (binaryJedisCluster.exists(getBytesKey(key))) {
            binaryJedisCluster.del(getBytesKey(key));
         }
         Map<byte[], byte[]> map = Maps.newHashMap();
         for (Map.Entry<String, Object> e : value.entrySet()) {
            map.put(e.getKey().getBytes(), toBytes(e.getValue()));
         }
         result = binaryJedisCluster.hmset(getBytesKey(key), map);
         if (cacheSeconds != 0) {
            binaryJedisCluster.expire(getBytesKey(key), cacheSeconds);
         }
         logger.debug("setObjectMap {} = {}", key, value);
      } catch (Exception e) {
         logger.warn("setObjectMap {} = {}", key, value, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 向Map缓存中添加值
    *
    * @param key   键
    * @param value 值
    * @return
    */
   public static String mapPut(String key, Map<String, String> value) {
      String result = null;
      
      try {
         Map<byte[], byte[]> map = Maps.newHashMap();
         for (Map.Entry<String, String> e : value.entrySet()) {
            map.put(e.getKey().getBytes(), e.getValue().getBytes());
         }
         result = binaryJedisCluster.hmset(getBytesKey(key), map);
         logger.debug("mapPut {} = {}", key, value);
      } catch (Exception e) {
         logger.warn("mapPut {} = {}", key, value, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 向Map缓存中添加值
    *
    * @param key   键
    * @param value 值
    * @return
    */
   public static String mapObjectPut(String key, Map<String, Object> value) {
      String result = null;
      
      try {
         
         Map<byte[], byte[]> map = Maps.newHashMap();
         for (Map.Entry<String, Object> e : value.entrySet()) {
            map.put((e.getKey()).getBytes(), toBytes(e.getValue()));
         }
         result = binaryJedisCluster.hmset(getBytesKey(key), map);
         logger.debug("mapObjectPut {} = {}", key, value);
      } catch (Exception e) {
         logger.warn("mapObjectPut {} = {}", key, value, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 移除Map缓存中的值
    *
    * @param key   键
    * @param value 值
    * @return
    */
   public static long mapRemove(String key, String mapKey) {
      long result = 0;
      try {
         result = binaryJedisCluster.hdel(getBytesKey(key), getBytesKey(mapKey));
         logger.debug("mapRemove {}  {}", key, mapKey);
      } catch (Exception e) {
         logger.warn("mapRemove {}  {}", key, mapKey, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 移除Map缓存中的值
    *
    * @param key   键
    * @param value 值
    * @return
    */
   public static long mapObjectRemove(String key, String mapKey) {
      long result = 0;
      
      try {
         result = binaryJedisCluster.hdel(getBytesKey(key), getBytesKey(mapKey));
         logger.debug("mapObjectRemove {}  {}", key, mapKey);
      } catch (Exception e) {
         logger.warn("mapObjectRemove {}  {}", key, mapKey, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 判断Map缓存中的Key是否存在
    *
    * @param key   键
    * @param value 值
    * @return
    */
   public static boolean mapExists(String key, String mapKey) {
      boolean result = false;
      
      try {
         
         result = binaryJedisCluster.hexists(getBytesKey(key), getBytesKey(mapKey));
         logger.debug("mapExists {}  {}", key, mapKey);
      } catch (Exception e) {
         logger.warn("mapExists {}  {}", key, mapKey, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 判断Map缓存中的Key是否存在
    *
    * @param key   键
    * @param value 值
    * @return
    */
   public static boolean mapObjectExists(String key, String mapKey) {
      boolean result = false;
      
      try {
         
         result = binaryJedisCluster.hexists(getBytesKey(key), getBytesKey(mapKey));
         logger.debug("mapObjectExists {}  {}", key, mapKey);
      } catch (Exception e) {
         logger.warn("mapObjectExists {}  {}", key, mapKey, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 删除缓存
    *
    * @param key 键
    * @return
    */
   public static long del(String key) {
      long result = 0;
      
      try {
         
         if (binaryJedisCluster.exists(getBytesKey(key))) {
            result = binaryJedisCluster.del(getBytesKey(key));
            logger.debug("del {}", key);
         } else {
            logger.debug("del {} not exists", key);
         }
      } catch (Exception e) {
         logger.warn("del {}", key, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 删除缓存
    *
    * @param key 键
    * @return
    */
   public static long delObject(String key) {
      long result = 0;
      
      try {
         
         if (binaryJedisCluster.exists(getBytesKey(key))) {
            result = binaryJedisCluster.del(getBytesKey(key));
            logger.debug("delObject {}", key);
         } else {
            logger.debug("delObject {} not exists", key);
         }
      } catch (Exception e) {
         logger.warn("delObject {}", key, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 缓存是否存在
    *
    * @param key 键
    * @return
    */
   public static boolean exists(String key) {
      boolean result = false;
      
      try {
         
         result = binaryJedisCluster.exists(getBytesKey(key));
         logger.debug("exists {}", key);
      } catch (Exception e) {
         logger.warn("exists {}", key, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 缓存是否存在
    *
    * @param key 键
    * @return
    */
   public static boolean existsObject(String key) {
      boolean result = false;
      
      try {
         
         result = binaryJedisCluster.exists(getBytesKey(key));
         logger.debug("existsObject {}", key);
      } catch (Exception e) {
         logger.warn("existsObject {}", key, e);
      } finally {
         
      }
      return result;
   }
   
   /**
    * 获取byte[]类型Key
    *
    * @param key
    * @return
    */
   public static byte[] getBytesKey(Object object) {
      if (object instanceof String) {
         return StringUtils.getBytes((String) object);
      } else {
         return ObjectUtils.serialize(object);
      }
   }
   
   /**
    * Object转换byte[]类型
    *
    * @param key
    * @return
    */
   public static byte[] toBytes(Object object) {
      return ObjectUtils.serialize(object);
   }
   
   /**
    * Object转换byte[]类型
    *
    * @param key
    * @return
    */
   public static String toString(Object object) {
      return ObjectUtils.serialize2Str(object);
   }
   
   /**
    * byte[]型转换Object
    *
    * @param key
    * @return
    */
   public static Object toObject(byte[] bytes) {
      return ObjectUtils.unserialize(bytes);
   }
   
   /**
    * String型转换Object
    *
    * @param key
    * @return
    */
   public static Object toObject(String str) {
      return ObjectUtils.unserialize(str);
   }
   
}
